package org.example.network.low.tcp;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

public class EchoServer {
    public static void main(String[] args) throws IOException {
        // 1. 创建ServerSocket实例，指定端口号
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务器启动，等待连接...");

        // 2. 等待客户端连接
        while (true){
            Socket socket = serverSocket.accept();
            System.out.println("客户端已连接");

            Thread thread = new Thread(()->{
                handleSocket(socket);
            });
            thread.start();
        }

        // 关闭ServerSocket
        // serverSocket.close();
    }

    private static void handleSocket(Socket socket)  {

        // 3. 获取输入输出流
        try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);){
            while (true) {
                // 4. 读取客户端发送的数据并响应
                String line = in.readLine();
                System.out.println("客户端发来的内容：" + line);
                out.println(line);
                System.out.println("返回给客户端的内容：" + line);

                // 5. 关闭资源
                if(Objects.equals(line, "bye bye")){
                    socket.close();
                    break;
                }
            }
        }catch (IOException ioe){
            ioe.printStackTrace();
        }
    }
}
